package com.example.testapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.testapplication.service.MyBinder;

import java.util.List;

public class BoundService extends AppCompatActivity {
    MyBinder binder;  //声明BinderService
    int[] tvid = {R.id.tView1,R.id.tView2,R.id.tView3,R.id.tView4,R.id.tView5,
            R.id.tView6,R.id.tView7};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bound_service);
        Button btn_random = (Button) findViewById(R.id.btn);

        btn_random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List number = binder.getRandomNumber(); //获取BinderService类中的随机数数组
                for(int i = 0; i < number.size(); i++){ //遍历数组并显示
                    TextView tv = (TextView) findViewById(tvid[i]); //获取文本框组件对象
                    String strNumber = number.get(i).toString();  //将获取的号码转为String类型
                    tv.setText(strNumber); //显示生成的随机号码

                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this,MyBinder.class);
        // 应用程序组件 能调用bindService 方法绑定到Service
        bindService(intent,conn,BIND_AUTO_CREATE); //绑定指定Service
    }
    @Override
    protected void onStop() {  //设置关闭Activity时解除与后台Service的绑定
        super.onStop();
        unbindService(conn);    //解除绑定Service
    }


    private ServiceConnection conn = new ServiceConnection() { //设置与后台Service进行通讯
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder = ((MyBinder.MyBind) iBinder).getService(); //获取后台Service信息
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
}